import { Toast } from "antd-mobile"
import { reqregister } from "../../http/api"


// state 
const initState = {
    user: {
        phone: "",
        nickname: "",
        password: ""
      }
}

// action type
const TYPES = {
    REGISTER_CHANGE_USER:"REGISTER_CHANGE_USER"
}

// reducer
const reducer = (state=initState,action) =>{
    switch(action.type){
        case TYPES.REGISTER_CHANGE_USER:
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
        default:
            return state
    }
}

// action creator
export const actions={
    changeUser:(key,value) => ({type:TYPES.REGISTER_CHANGE_USER,key,value}),
    doRegister:(push)=>{
        return (dispantch,getState)=>{
            let user = getUser(getState())
            reqregister(user).then(res=>{
                if(res.data.code===200){
                    Toast.show({
                        content:res.data.msg
                    })
                    push("/login")
                }
            })
        }
    }
}

// selector导出数据给组件
export const getUser = state => state.register.user

// 导出reducer
export default reducer